package net.bluesword.practice007.service;


import net.bluesword.practice007.dao.AuthorityRepository;
import net.bluesword.practice007.dao.CustomerRepository;
import net.bluesword.practice007.domain.Customer;
import net.bluesword.practice007.domain.TblAuthority;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CustomerService {
    @Autowired
    private CustomerRepository customerReppository;
//
    @Autowired
    private AuthorityRepository authorityRepository;

    @Autowired
    private RedisTemplate redisTemplate;

    public Customer getCustomer(String username)
    {
        Customer customer=null;
        Object o = redisTemplate.opsForValue().get("customer_" + username);
        if (o != null) {
            customer= (Customer) o;
        }
        else {
            customer = customerReppository.findByUsername(username);
            if (customer != null)
            {
                redisTemplate.opsForValue().set("customer_"+username,customer);
            }
        }
        return customer;
    }

    public List<TblAuthority> getCustomerAuthority(String username)
    {
        List<TblAuthority> authorities=null;
        Object o = redisTemplate.opsForValue().get("authorities_" + username);
        if (o != null) {
            authorities= (List<TblAuthority>) o;
        }
        else {
            authorities = authorityRepository.findAuthoritiesByUsername(
                    username);
            if (authorities != null && authorities.size()>0)
            {
                redisTemplate.opsForValue().set("authorities_"+username,authorities);
            }
        }
        return authorities;
    }


}
